<template>
    <eui-page-frame :topHeight="250" :bottomHeight="80"  withOutBorder="true">
        <template #top>
            <view class="content-img">
                <eui-navbar ref="euiNavBar" title="集单收货" :storeName="getRelatedName('rdsStores', sUserStore)"
                            :storeId="sUserStore" :displayable="true"
                            color="#000000" backgroundColor="#FFFFFF">
                    <template v-slot:popupContent>
                        <view class="custom-menu">
                            <view class="setting-item">
                                <eui-card-input v-model="inputMode" title="开启追单" @input="toggleMode"
                                                type="radio" :range="inputModeRange"/>
                            </view>
                        </view>
                        <view class="setting-desc">
                            <ul style="margin: 2em;padding: 0em">
                                <li>追单说明
                                    <ul style="margin: 0.5em;padding: 0em">
                                        <li>开启：若集单中没有扫描的商品，则弹出商品录入框</li>
                                        <li>关闭：若集单中有扫描的商品，则弹出商品选择框</li>
                                    </ul>
                                </li>
                                <li>集单说明：集单必须是同一供应商、同一收货仓库</li>
                            </ul>
                        </view>
                    </template>
                </eui-navbar>
                <view class="top-view">
                    <eui-search-bar ref="RdsSearchBar" placeholder="请输入商品编码、条码、单据号" @confirm="searchConfirm"
                                    v-model="searchText" radius="30"/>
                </view>
            </view>
        </template>
        <eui-page-content>
            <view class="footer-view">
                <eui-card title="基本信息" showTitleLine="true" h-padding="20">
                    <template v-slot:extra>
                        <view class="extra-view" @click="changeBasicStatus">
                            <eui-uicons :type="showBasic ? 'up' : 'down'" size="24"/>
                        </view>
                    </template>
                    <eui-card-input style="padding: 16rpx 0rpx;" v-model="mainData.c_po_id" title="订单号" rightIconType="right"
                                    @iconClick="clickRight('c_po_id')" occupy/>
                    <view class="m-main-top" v-if="showBasic">
                        <eui-text v-model="mainData.c_id" type="name" title="验收单号" occupy/>
                        <eui-text v-model="mainData.c_provider" type="titlename" title="供应商"
                                  :name="getRelatedName('rdsProviders', mainData.c_provider)" occupy/>
                        <eui-text v-model="c_n_rec_total" type="price" title="已收正品数量"/>
                        <eui-text v-model="c_sku_rec_total" type="name" title="已收品种数"/>
                        <eui-text v-model="c_n_rec_free_total" type="price" title="已收赠品数量"/>
                    </view>
                </eui-card>
                <eui-card title="当前商品" showTitleLine="true" h-padding="20" type="detail">
                    <view @click="onClickGdsInfo(currentGds)">
                        <view class="m-main-top">
                            <eui-text
                                :value="currentGds.c_gcode ? '[' + currentGds.c_gcode + ']' + currentGds.c_gname : ''"
                                type="name" title="当前商品" occupy/>
                            <eui-text v-model="currentGds.c_barcode" type="name" title="条码"/>
                            <eui-text v-model="currentGds.c_order_pack" type="slash" :name="currentGds.c_order_unit"
                                      title="含量/单位"/>
                            <eui-text v-model="currentGds.c_n_confirm" type="price" title="订货数量" :precision="3"/>
                            <eui-text v-model="currentGds.c_n_free_confirm" type="price" title="赠品数量(订)"
                                      :precision="3"/>
                            <eui-text :value="currentGds.c_n" type="price" title="收货数量" :precision="3"/>
                            <eui-text :value="currentGds.c_n_free" type="price" title="赠品数量(收)" :precision="3"/>
                            <eui-text :value="currentGds.c_product_dt" type="date" title="生产日期"/>
                            <eui-text :value="currentGds.c_expired_dt" type="date" title="限用日期"/>
                            <!-- <eui-text :value="currentGds.c_note" type="name" title="备注" /> -->
                        </view>
                    </view>
                </eui-card>
                <view v-if="!showDiff">
                    <eui-card title="商品验收" showTitleLine="true" h-padding="20" type="detail">
                        <eui-swipe-action>
                            <view :id="`item-${index}`"
                                  v-for="(item, index) in listManager"
                                  :key="index" @click="onClickGdsInfo(item, index)"
                                  style="background-color:#ffffff">
                                <eui-swipe-actionitem :right-options="options"
                                                      :disabled="mainData.c_status !== '0' || mainData.c_approve_status !== '1'"
                                                      show="none"
                                                      :auto-close="true" @change="change"
                                                      @click="bindClick($event, index)">
                                    <view class="m-list-top">
                                        <eui-text :value="'[' + item.c_gcode + ']' + item.c_gname" type="name"
                                                  :title="index + 1 + '. 商品'" occupy/>
                                        <eui-text v-model="item.c_barcode" type="name" title="条码"/>
                                        <eui-text v-model="item.c_order_pack" type="slash" :name="item.c_order_unit"
                                                  title="含量/单位"/>
                                        <!-- <eui-text v-model="item.c_at_pay_order" type="price" title="订货结算额" />
                            <eui-text v-model="item.c_at_pay" title="收货结算额" type="price" />
                            <eui-text :value="item.c_n_pack" :name="item.c_n_odd" type="rdsslash" title="收货件/零数" /> -->
                                        <eui-text v-model="item.c_n_confirm" type="price" title="订货数量"/>
                                        <eui-text v-model="item.c_n_free_confirm" type="price"
                                                  title="赠品数量(订)"/>
                                        <eui-text v-model="item.c_n" type="price" title="收货数量"
                                                  :style="(item.c_n !== 0 && item.c_n_confirm !== item.c_n) ? 'color: red' : 'color : black'"/>
                                        <eui-text v-model="item.c_n_free" type="price" title="赠品数量(收)"/>
                                        <!-- <eui-text :value="item.c_od_day + getDictName('保质期单位', item.c_od_unit)" type="name"
                                title="保质期" /> -->
                                        <!-- <eui-text v-model="item.c_pt_pay" type="price" title="结算价" /> -->
                                        <eui-text v-model="item.c_product_dt" type="date" title="生产日期"/>
                                        <eui-text v-model="item.c_expired_dt" type="date" title="限用日期"/>
                                        <eui-text v-model="item.c_serial_no" type="name" title="批号/串码" occupy/>
                                        <eui-text v-model="item.c_note" type="name" title="备注"/>
                                        <!-- <eui-text v-model="JSON.parse(item.c_err_msg)[0].c_msg_err" type="name"
                                        v-if="item.c_err_msg" title="错误" style="white-space: pre-wrap;color: red;"
                                        occupy /> -->
                                    </view>
                                </eui-swipe-actionitem>
                            </view>
                        </eui-swipe-action>
                        <view v-if="listManager.length===0">
                            <image src="@/static/img/no_data.png" mode="aspectFit" class="image-min"/>
                            <view class="no-data-text">暂无数据</view>
                        </view>
                    </eui-card>
                </view>
                <view v-show="showDiff">
                    <eui-card title="商品验收差异" showTitleLine="true" h-padding="20" type="detail">
                        <view :id="`item-${index}`"
                              v-for="(item, index) in diffListManager"
                              :key="index" @click="onClickGdsInfo(item, index)">
                            <view class="m-list-top">
                                <eui-text :value="'[' + item.c_gcode + ']' + item.c_gname" type="name"
                                          :title="index + 1 + '. 商品'" occupy/>
                                <eui-text v-model="item.c_barcode" type="name" title="条码"/>
                                <eui-text v-model="item.c_order_pack" type="slash" :name="item.c_order_unit"
                                          title="含量/单位"/>
                                <eui-text v-model="item.c_n_confirm" type="price" title="订货数量"/>
                                <eui-text v-model="item.c_n_free_confirm" type="price" title="赠品数量(订)"/>
                                <eui-text v-model="item.c_n" type="price" title="收货数量" style="color: red;"/>
                                <eui-text v-model="item.c_n_free" type="price" title="赠品数量(收)"/>
                                <eui-text v-model="item.c_product_dt" type="date" title="生产日期"/>
                                <eui-text v-model="item.c_expired_dt" type="date" title="限用日期"/>
                                <eui-text v-model="item.c_serial_no" type="name" title="批号/串码" occupy/>
                                <eui-text v-model="item.c_note" type="name" title="备注"/>
                                <!-- <eui-text v-model="JSON.parse(item.c_err_msg)[0].c_msg_err" type="name"
                                v-if="item.c_err_msg" title="错误" style="white-space: pre-wrap;color: red;" occupy /> -->
                            </view>
                        </view>
                        <view v-if="diffListManager.length===0">
                            <image src="@/static/img/no_data.png" mode="aspectFit" class="image-min"/>
                            <view class="no-data-text">暂无数据</view>
                        </view>
                    </eui-card>
                </view>
            </view>
            <eui-popup ref="gdsPopup" background-color="#f8f8f8" type="bottom" :safe-area="true"
                       borderRadius="10px 10px 0 0" :mask-click="true">
                <view class="popup-content">
                    <view class="popup-title">详情</view>
                    <view class="m-list-top">
                        <eui-text :value="'[' + currentGds.c_gcode + ']' + currentGds.c_gname" type="name"
                                  title="商品" occupy/>
                        <eui-text v-model="currentGds.c_barcode" type="name" title="条码"/>
                        <eui-text v-model="currentGds.c_order_pack" type="slash" :name="currentGds.c_order_unit"
                                  title="含量/单位"/>
                        <!-- <eui-text v-model="currentGds.c_at_pay_order" type="price" title="订货结算额" /> -->
                        <eui-text v-model="currentGds.c_n_confirm" type="price" title="订货数量"
                                  :precision="3"/>
                        <eui-text v-model="currentGds.c_n_free_confirm" type="price" title="赠品数量"
                                  :precision="3"/>
                        <!-- <eui-text v-model="currentGds.c_at_pay" title="收货结算额" type="price" /> -->
                        <eui-text :value="currentGds.c_n_pack" type="price" title="件数"
                                  v-if="!(currentGds.c_order_pack > 1) || (mainData.c_status !== '0' || mainData.c_approve_status !== '1')"/>
                        <eui-text :value="currentGds.c_n_odd" type="price" title="零数"
                                  v-if="!(currentGds.c_order_pack > 1) || (mainData.c_status !== '0' || mainData.c_approve_status !== '1')"/>
                        <eui-text :value="currentGds.c_od_day + getDictName('保质期单位', currentGds.c_od_unit)"
                                  type="name" title="保质期"/>
                    </view>
                    <view class="m-list-top"
                          v-if="mainData.c_status !== '0' || mainData.c_approve_status !== '1'">
                        <eui-text :value="currentGds.c_n" type="price" title="数量" :precision="3"/>
                        <eui-text :value="currentGds.c_n_free" type="price" title="赠品数量" :precision="3"/>
                        <eui-text :value="currentGds.c_product_dt" type="date" title="生产日期"/>
                        <eui-text :value="currentGds.c_expired_dt" type="date" title="限用日期"/>
                        <eui-text :value="currentGds.c_serial_no" type="name" title="批号"/>
                        <eui-text :value="currentGds.c_note" type="name" title="备注"/>
                    </view>
                    <view v-if="mainData.c_status === '0' && mainData.c_approve_status === '1'">
                        <eui-card-input v-model="currentGds.c_n_pack" title="件数" type="number" isBlur
                                        fieldName="c_n_pack" @confirm="validateDetail" ref="cardNPackInput"
                                        placeholder="请输入件数" v-if="currentGds.c_order_pack > 1"/>
                        <eui-card-input v-model="currentGds.c_n_odd" title="零数" type="number" isBlur
                                        fieldName="c_n_odd" @confirm="validateDetail" ref="cardNOddInput"
                                        placeholder="请输入零数" v-if="currentGds.c_order_pack > 1"/>
                        <eui-card-input v-model="currentGds.c_n" title="数量" type="number" isBlur
                                        fieldName="c_n" focus="true"
                                        @confirm="validateDetail" ref="cardRecNInput"
                                        placeholder="请输入收货数量" required
                                        :style="currentGds.c_n < 0 ? 'color: red' : 'color: black'"/>
                        <eui-card-input v-model="currentGds.c_n_free" title="赠品数量" type="number" isBlur
                                        fieldName="c_n_free" @confirm="validateDetail" ref="cardNFreeInput"
                                        placeholder="请输入赠品数量"/>
                        <eui-card-input v-model="currentGds.c_serial_no" title="批号/串码" type="text"/>
                        <eui-card-input :value="currentGds.c_product_dt" title="生产日期" type="date"
                                        @input="productDtChanged" ref="productDtInput" rightIconType="clear"/>
                        <eui-card-input :value="currentGds.c_expired_dt" title="限用日期" type="date"
                                        @input="expiredDtChanged" ref="expiredDtInput" rightIconType="clear"/>
                        <!-- <eui-card-input v-model="currentGds.c_pt_pay" title="结算价" type="number" isBlur
                            fieldName="c_pt_pay" @confirm="validateDetail" ref="cardPtPayInput"
                            :displayable=c_disabled /> -->
                        <eui-card-input v-model="currentGds.c_note" title="备注" type="text" fieldName="c_note"
                                        maxlength="300"/>
                    </view>
                    <view class="bt-button">
                        <eui-button type="max2" single-tag="cancel" title="关闭" @buttonClick="buttonClick"/>
                        <eui-button type="max" single-tag="submit3" title="确认" @buttonClick="buttonClick"
                                    :disabled="mainData.c_status !== '0' || mainData.c_approve_status !== '1'"/>
                    </view>
                </view>
            </eui-popup>
            <eui-popup ref="orderPopup" background-color="#f8f8f8" type="bottom" :mask-click="true">
                <view class="popup-content">
                <view class="popup-title">订单号</view>
                    <scroll-view :scroll-top="0" scroll-y="true">
                        <eui-swipe-action>
                            <view v-for="(item, index) in mainDataList" :key="index"
                                  @click="onClickOrderInfo(item, index)">
                                <eui-swipe-actionitem :right-options="options"
                                                      :disabled="mainDataCollection.c_status === '2'"
                                                      show="none"
                                                      :auto-close="true" @change="change"
                                                      @click="bindClickCollection($event, index)">
                                    <view :ref="`view${index}`" class="m-list-top">
                                        <eui-text v-model="item.c_po_id" type="name"
                                                  :title="`${1 + index}. 订单号`" occupy/>
                                        <eui-text v-model="item.c_id" type="name" title="验收单号" occupy/>
                                        <eui-text v-model="item.c_provider" type="titlename" title="供应商"
                                                  :name="getRelatedName('rdsProviders', item.c_provider)"
                                                  occupy/>
                                    </view>
                                </eui-swipe-actionitem>
                            </view>
                        </eui-swipe-action>
                    </scroll-view>
                    <view class="bt-button">
                        <eui-button type="max2" single-tag="cancel" title="关闭" @buttonClick="buttonClick"/>
                        <eui-button type="max" single-tag="deleteRecCollection" title="删除集单" @buttonClick="buttonClick"/>
                    </view>
                </view>
            </eui-popup>
            <eui-popup ref="popupMessage" background-color="#f8f8f8" type="center">
                <view class="popup-content">
                    <view class="popup-title">提示</view>
                    <view v-for="(item, index) in processInFos" :key="index">
                        <eui-text :value="index + 1 + '. ' + item.BillId" type="id" title="单号"/>
                        <eui-text :value="item.ErrInFo" type="name" style="white-space: pre-wrap;color:red"
                                  title="错误信息"/>
                    </view>
                </view>
            </eui-popup>
        </eui-page-content>
        <template #bottom>
            <view class="bt-button">
                <eui-button type="min" single-tag="showDiff" title="显示差异" v-show="!showDiff"
                            @buttonClick="buttonClick"/>
                <eui-button type="min" single-tag="showDiff" title="显示原始" v-show="showDiff"
                            @buttonClick="buttonClick"/>
                <eui-button type="min" single-tag="detail" title="收货详情"
                            @buttonClick="buttonClick"/>
                <eui-button type="min" single-tag="submit" title="提交"
                            :disabled="['3', '9'].includes(mainData.c_status) || mainData.c_approve_status !== '1'"
                            @buttonClick="buttonClick"/>
            </view>
        </template>
    </eui-page-frame>
</template>

<script setup type="ts">
import {ref, reactive, onMounted} from 'vue';
import dayjs from 'dayjs';
import service from "@/common/service";
import {getRelatedName, getDictList, getDictName} from '../components/RelatedName.js';
import {getRdsSysConfig} from '@/hooks/init';
import {groupBy} from '@/hooks/useUtils';
import {useWeightUnits} from '@/hooks/useWeightUnits'
import {calcAtInByPt, calculatePackages, calcPtInByPtPay, calcPetpayByPtPay} from '@/hooks/useCalculateMethod';
import {dateDiff, dateAdd, todayAdd, isDomesticBarcode} from '@/hooks/useUtils';
import {mapState, mapMutations} from 'vuex';
import {getRdsUrl, rdsRequest, rdsRequestAsync} from '@/hooks/rdsServices';
import {onLoad} from "@dcloudio/uni-app";
import {useMainStore} from "@/store/modules/store";
import {useLoginStore} from "@/store/modules/useLoginStore";
import {set} from "vue-demi";

const rdsUrl = getRdsUrl();
const {weightUnits} = useWeightUnits();
const mainStore = useMainStore();
const {loginInfo} = mainStore;
const loginStore = useLoginStore();

const sUserStore = ref('');
const c_sku_rec_total = ref(0);
const c_n_rec_total = ref(0);
const c_n_rec_free_total = ref(0);
const title = ref('我要收货');
const showBasic = ref(true);
const gdsPopup = ref(null);
const orderPopup = ref(null);
const popupMessage = ref(null);

const cardNPackInput = ref(null);
const cardNOddInput = ref(null);
const cardRecNInput = ref(null);
const cardNFreeInput = ref(null);
const cardPtPayInput = ref(null);
const RdsSearchBar = ref(null);


const c_gcode = ref('');
const c_disabled = ref(false);
const search_bar_disabled = ref(false);
const c_status = ref('0');
const showDiff = ref(false);
const isCurrentGds = ref([]);
const searchText = ref('');
const selectType = ref('');
const inputMode = ref('1');
const inputModeRange = ref([{
    value: '1',
    text: '开启',
    checked: 'true'
},
    {
        value: '2',
        text: '关闭'
    }
]);
const options = ref([{
    text: '删除',
    style: {
        backgroundColor: '#F56C6C',
    }
},]);
const sysConfig = ref({
    policyD: '', //永续订单验收进价控制策略；0-不可更改，1-可改低，2-可任意修改
    policyN: '', //无订单验收进价控制策略；0-不可更改，1-可改低，2-可任意修改
    policyO: '', //正常订单验收进价控制策略；0-不可更改，1-可改低，2-可任意修改
    policyP: '', //促销订单验收进价控制策略；0-不可更改，1-可改低，2-可任意修改
    policyC: '', //变价订单验收进价控制策略；0-不可更改，1-可改低，2-可任意修改
    ptInMinTimes: 0, //验收进价异常下限倍数
    ptInMaxTimes: 0, //验收进价异常上限倍数
    isMustInputPdt: '', //有保质期商品是否必须录入生产日期；0-否；1-是
    minExpiredPercent: 0, //允许收货的留存时间占保质期的最低百分比
    exceedOutDate: '', //保质期报警天数,生产日期+保质期距当前日期天数大于保质期报警天数则报警
    mustInputPdtExceptAdnos: [], //必须录入生产日期的例外部门
    recOverOrderRate: 0, //验收数量最多可超过订货数量比例
    isPeriod: false, //是否开启保质期控制
    canOverOrderClass: [], //验收数量可超过订货数量的品类
});
const currentGds = ref({});
const currentGdsIndex = ref(0);
const mainData = ref({});
const mainDataList = ref([]);
const detailData = ref([]);
const detailDataList = ref([]);
const listManager = ref([]);
//集单收货数据
const mainDataCollection = ref({});
const detailDataCollection = ref([]);

//当前集单号下所有的验收单号
const detailDataCollectionRecId = ref([]);
//分组后的数据
const groupData = ref([]);
//当前用户验收的商品编码
const middleBarCodeList = ref([]);
const processInFos = ref([]);
const diffListManager = ref([]);

onLoad(async (option) => {
    sUserStore.value = option.storeId;
    mainData.value.c_id = option.c_id;
    c_gcode.value = option.c_gcode;
    if (option.c_id) {
        service.enjoyShowLoading('正在加载...');
        await chooseOrder(option.c_id);
        service.enjoyHideLoading();
    }
    await getSysConfig();
})

const getSysConfig = async () => {
    sysConfig.value.policyD = await getRdsSysConfig("商品验收控制参数", "永续订单验收进价控制策略");
    sysConfig.value.policyN = await getRdsSysConfig("商品验收控制参数", "无订单验收进价控制策略");
    sysConfig.value.policyO = await getRdsSysConfig("商品验收控制参数", "正常订单验收进价控制策略");
    sysConfig.value.policyP = await getRdsSysConfig("商品验收控制参数", "促销订单验收进价控制策略");
    sysConfig.value.policyC = await getRdsSysConfig("商品验收控制参数", "变价订单验收进价控制策略");
    sysConfig.value.ptInMinTimes = Number(await getRdsSysConfig("商品验收控制参数", "验收进价异常下限倍数"));
    sysConfig.value.ptInMaxTimes = Number(await getRdsSysConfig("商品验收控制参数", "验收进价异常上限倍数"));
    sysConfig.value.isMustInputPdt = await getRdsSysConfig("商品验收控制参数", "有保质期商品是否必须录入生产日期");
    sysConfig.value.minExpiredPercent = Number(await getRdsSysConfig("商品验收控制参数", "允许收货留存时间占保质期的最低百分比"));
    sysConfig.value.exceedOutDate = Number(await getRdsSysConfig("商品验收控制参数", "保质期报警天数"));
    sysConfig.value.mustInputPdtExceptAdnos = await getDictList("有保质期商品是否必须录入生产日期的例外部门");
    sysConfig.value.recOverOrderRate = Number(await getRdsSysConfig("商品验收控制参数", "验收数量最多可超过订货数量比例"));
    sysConfig.value.isPeriod = await getRdsSysConfig("商品验收控制参数", "是否开启保质期控制") === '1';
    sysConfig.value.canOverOrderClass = await getDictList("验收数量可超过订货数量的品类");
};
const searchConfirm = async (e) => {
    searchText.value = e.value;
    console.log("inputMode", inputMode)
    if (searchText.value.length === 7) {
        const gdsInfo = await getGdsInfo(searchText.value);
        c_gcode.value = gdsInfo.c_barcode;
    } else {
        c_gcode.value = searchText.value;
    }
    
    if (inputMode.value === '1') {
        await billListByGCode();
        middleBarCodeList.value.push(c_gcode.value);
        return;
    }
    const itemIndex = groupData.value.findIndex(x => x.c_barcode === c_gcode.value);
    if (itemIndex !== -1) {
        await onClickGdsInfo(groupData.value[itemIndex], itemIndex)
    }
};
const changeBasicStatus = () => {
    showBasic.value = !showBasic.value;
}
const getPtPolicy = async () => {
    let ptPolicy = '';
    const priceType = mainData.value?.c_src_type?.startsWith('5F') ? 'D' : mainData.value?.c_price_type
    //0-正常订单、1-首单折扣订单、2-可变价订单、3-促销订单、9-无订单
    switch (priceType) {
        case '0':
        case '1':
            ptPolicy = sysConfig.value.policyO;
            break;
        case '2':
            ptPolicy = sysConfig.value.policyC;
            break;
        case '3':
            ptPolicy = sysConfig.value.policyP;
            break;
        case '9':
            ptPolicy = sysConfig.value.policyN;
            break;
        case 'D':
            ptPolicy = sysConfig.value.policyD;
            break;
        default:
            ptPolicy = sysConfig.value.policyO;
            break;
    }
    if (ptPolicy === '0') {
        c_disabled.value = true;
    }
    return ptPolicy;
};
// 选择框点击事件
const clickRight = async (type) => {
    
    console.log("type", type)
    selectType.value = type;
    if (type === 'c_store_id') {
        await uni.navigateTo({
            url: '../modals/store/index'
        });
    } else if (type === 'c_po_id') {
        if (!sUserStore.value) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '请先选择机构'
            });
            return false;
        }
        orderPopup.value.open('bottom');
        // 选择订单
        // await uni.navigateTo({
        //     url: '../modals/recOrder/index?storeId=' + sUserStore.value
        // });
    } else if (type === 'c_store_id_name') {
        await uni.navigateTo({
            url: '../modals/store/index'
        });
    }
};
const onClickGdsInfo = async (item, index) => {
    console.log("item, index", item, index)
    if (!item.c_gcode) {
        return;
    }
    // if (mainData.value.c_status !== '0') {
    //     return;
    // }
    // currentGds.valueIndex = groupData.value.findIndex(x => x.c_id === item.c_id && x.c_barcode === item.c_barcode);
    currentGds.value = JSON.parse(JSON.stringify(item));
    gdsPopup.value.open('bottom');
    // const isDomestic = isDomesticBarcode(currentGds.value.c_barcode);
    // if (isDomestic) {
    //     c_disabled.value = true
    //     // $refs.productDtRef.getFocus();
    // } else {
    //     c_disabled.value = false
    //     // $refs.expiredDtRef.getFocus();
    // }
    
};
const onClickOrderInfo = async (item, index) => {
    // mainData.value = mainDataList.value.find(x => x.c_id === item.c_id);
    // listManager.value = detailData.value.filter(x => x.c_id === item.c_id);
    // service.enjoyShowLoading('正在加载...');
    // orderPopup.value.close();
    // calcMainAmount(item.c_id);
    // setClass(index);
    // service.enjoyHideLoading();
    // $refs[`view${index}`][0].style.backgroundColor = '#FDFFC2E0';
};
// 扫码
const clickScanRight = async (type) => {
    if (type === "c_gcode") {
        await uni.scanCode({
            success: async function (res) {
                if (res.result) {
                    c_gcode.value = res.result;
                    searchText.value = res.result;
                    await searchConfirm(res.result);
                }
            }
        });
    }
};

const SelectionChanged = async (type, item) => {
    console.log("type,item", type, item)
    switch (type) {
        case 'c_store_id':
            sUserStore.value = item.c_store_id;
            break;
        case 'poId':
            service.enjoyShowLoading('正在加载...');
            //判断是否已有该订单
            const itemIndex = mainDataList.value?.find(x => x.c_id === item.c_id);
            if (itemIndex && itemIndex !== -1) {
            } else {
                await chooseOrder(item.c_id);
            }
            //自动弹出扫描的商品
            await openGdsPopup();
            service.enjoyHideLoading();
            break;
        case '' :
    }
};
defineExpose({
    SelectionChanged
})
const openGdsPopup = async () => {
    const itemIndex = listManager.value.findIndex(x => x.c_barcode === c_gcode.value);
    if (itemIndex !== -1) {
        await onClickGdsInfo(listManager.value[itemIndex], itemIndex)
        return;
    } else {
        const itemIndex = groupData.value.findIndex(x => x.c_barcode === c_gcode.value);
        if (itemIndex !== -1) {
            await onClickGdsInfo(groupData.value[itemIndex], itemIndex)
            return;
        }
    }
};
const validateDetail = async (args) => {
    console.log("args", args)
    const {type, fieldName, oldValue, newValue, itemIndex} = args;
    let result = null;
    switch (fieldName) {
        case 'c_pt_pay':
            const pt_pay = newValue;
            //0-不可更改，1-可改低，2-可任意修改
            const ptPolicy = await getPtPolicy();
            if (ptPolicy === '0') {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '当前结算价不允许调整'
                });
                setTimeout(() => {
                    currentGds.value.c_pt_pay = oldValue;
                    cardPtPayInput.value.inputValue = oldValue;
                }, 300);
                break;
            } else if (ptPolicy === '1' && newValue > currentGds.value.c_pt_pay) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '结算价不允许调高'
                });
                setTimeout(() => {
                    currentGds.value.c_pt_pay = oldValue;
                    cardPtPayInput.value.inputValue = oldValue;
                    cardPtPayInput.value.getFocus()
                }, 300);
                break;
            }
            if (sysConfig.value.ptInMaxTimes !== 0) {
                if (pt_pay > currentGds.value.c_pt_pay_con * sysConfig.value.ptInMaxTimes) {
                    await uni.showToast({
                        duration: 2000,
                        icon: 'none',
                        title: `当前结算价与合同结算价相比，超出上限倍数[${sysConfig.value.ptInMaxTimes}]的限制！`
                    });
                    setTimeout(() => {
                        currentGds.value.c_pt_pay = oldValue;
                        cardPtPayInput.value.inputValue = oldValue;
                        cardPtPayInput.value.getFocus()
                    }, 300);
                    break;
                }
            }
            if (sysConfig.value.ptInMinTimes !== 0) {
                if (pt_pay < currentGds.value.c_pt_pay_con / sysConfig.value.ptInMinTimes) {
                    await uni.showToast({
                        duration: 2000,
                        icon: 'none',
                        title: `当前结算价与合同结算价[${currentGds.value.c_pt_pay_con}]相比，低于下限倍数[${sysConfig.value.ptInMinTimes}]的限制！`
                    });
                    setTimeout(() => {
                        cardPtPayInput.value.getFocus()
                    }, 300);
                    break;
                }
            }
            currentGds.value.c_pt_pay = pt_pay
            currentGds.value.c_pt_in = calcPtInByPtPay({
                c_pt_pay: pt_pay,
                c_tax_rate: currentGds.value.c_tax_rate,
                c_tax_rate_pay: currentGds.value.c_tax_rate_pay,
                c_tax_src: currentGds.value.c_tax_src
            })
            
            currentGds.value.c_pet_pay = calcPetpayByPtPay({
                c_pt_pay: pt_pay,
                c_tax_rate_pay: currentGds.value.c_tax_rate_pay,
                c_tax_src: currentGds.value.c_tax_src
            });
            await calcRowAmount();
            break;
        case 'c_n':
            const recN = newValue;
            currentGds.value.c_n = recN;
            if (!weightUnits.value.includes(currentGds.value.c_order_unit)) {
                if (recN % 1 > 0) {
                    await uni.showToast({
                        duration: 2000,
                        icon: 'none',
                        title: '本商品验收数量不允许录入小数，仅重量单位商品可以录入小数'
                    });
                    setTimeout(() => {
                        currentGds.value.c_n = oldValue;
                        cardRecNInput.value.inputValue = oldValue;
                        cardRecNInput.value.getFocus()
                    }, 300);
                    return;
                }
            }
            const overResult = await canOverOrderValidate(currentGds.value.c_ccode, currentGds.value.c_n_confirm, recN,)
            if (!overResult) {
                setTimeout(() => {
                    currentGds.value.c_n = oldValue;
                    cardRecNInput.value.inputValue = oldValue;
                    cardRecNInput.value.getFocus()
                }, 300);
                return
            }
            const result = await calculatePackages(currentGds.value.c_order_pack, recN);
            currentGds.value.c_n_pack = result.npack;
            currentGds.value.c_n_odd = result.odd;
            await calcRowAmount();
            break;
        case 'c_n_free':
            const recFreeN = newValue;
            currentGds.value.c_n_free = recFreeN;
            await calcRowAmount();
            break;
    }
};
const buttonClick = async (e) => {
    const {singleTag, modelValue, type} = e;
    switch (singleTag) {
        case 'showDiff':
            diffListManager.value = [
                ...(listManager.value.filter(item => item.c_n_confirm !== item.c_n && item.c_n !== 0))
            ];
            console.log("diffListManager.value",diffListManager.value)
            showDiff.value = !showDiff.value;
            break;
        case 'submit':
            // 提交
            if (listManager.value.length <= 0) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '商品不能为空！'
                });
                return false;
            }
            
            //生产日期不能为空
            // const filterList = detailData.value.filter(item => item.c_product_dt === '' || item.c_product_dt === null);
            // const gcodes = filterList.map(item => item.c_gcode);
            // if (gcodes.length > 0) {
            //     await uni.showToast({
            //         icon: 'none',
            //         title: `商品${gcodes}生产日期不能为空！请检查`,
            //     });
            //     return false;
            // }
            
            //验证保持和rds一致，先注释
            // const result = validateBarcode();
            // if (!result) {
            //     return false;
            // }
            
            const confirmFlag = await enjoyConfirm('请确认，提交验收的商品?');
            if (!confirmFlag) {
                return;
            }
            service.enjoyShowLoading('正在提交...');
            const submitResult = await submitBill();
            if (submitResult) {
                middleBarCodeList.value = [];
                await billQueryMiddle('0');
            }
            currentGds.value = {};
            service.enjoyHideLoading();
            RdsSearchBar.value.clear();
            break;
        case 'detail':
            await uni.navigateTo({
                url: './detail?collectionId=' + mainDataCollection.value.c_id +
                    '&storeId=' + mainData.value.c_store_id
            });
            break
        case 'cancel':
            gdsPopup.value.close()
            orderPopup.value.close()
            setTimeout(() => {
                // RdsSearchBar.value.clear();
            }, 300);
            break;
        case 'submit3':
            // if (c_disabled) {
            //     if (!validateProductDt(currentGds.value.c_product_dt)) {
            //         return;
            //     }
            // } else {
            //     if (!validateExpiredDt(currentGds.value.c_expired_dt)) {
            //         return;
            //     }
            // }
            if (sysConfig.value.isMustInputPdt === '1' && //参数：有保质期商品是否必须录入生产日期
                currentGds.value.c_od_day > 0 && //保质期大于0
                !currentGds.value.c_product_dt && //生产日期为空
                (currentGds.value.c_n_free > 0 || //赠品收获数量
                    currentGds.value.c_n > 0) && //收货数量
                !sysConfig.value.mustInputPdtExceptAdnos.some(adno => currentGds.value.c_adno
                    .startsWith(
                        adno.value)) //排除例外部门的
            ) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: '商品有保质期管理，请录入生产日期'
                });
                return;
            }
            //开启保质期控制
            if (sysConfig.value.isPeriod) {
                //查询验收记账单
                const result = await rdsRequest(rdsUrl.scApi, '商品验收单', 'QueryRecGaByCode', currentGds.value.c_gcode, 'S01');
                if (result !== null && result.c_product_dt > currentGds.value.c_product_dt) {
                    await uni.showToast({
                        duration: 2500,
                        icon: 'none',
                        title: `已开启保质期控制，生产日期不可小于最后验收的生产日期:${result.c_product_dt.substring(0, 10)}`
                    });
                    return;
                }
            }
            
            if (currentGds.value.c_n_free > 0 && currentGds.value.c_n === 0) {
                let flag = await enjoyConfirm("当前录入为赠品数量，是否确认？");
                if (!flag) {
                    return;
                }
            }
            service.enjoyShowLoading("正在加载...");
            try {
                const saveResult = await saveBillMiddle({
                    middleItem: currentGds.value
                });
                if (!saveResult) {
                    return;
                }
                
                const itemIndex = listManager.value.findIndex(item => item.c_gcode === currentGds.value.c_gcode && item.c_barcode === currentGds.value.c_barcode);
                if (itemIndex === -1) {
                    console.log("23123131312")
                    // await saveBillMiddle({ newItem: currentGds.value });
                    listManager.value.push(currentGds.value);
                } else {
                    // await saveBillMiddle({ modifiedItem: currentGds.value });
                    set(listManager.value, itemIndex, currentGds.value)
                }
                console.log("currentGds.value",currentGds.value)
                console.log("listManager.value",listManager.value)
                // await billQueryMiddle('0');
                await chooseOrder(mainData.value.c_id);
                
                
                // $set(detailData.value, currentGds.valueIndex, currentGds.value)
                gdsPopup.value.close();
                await calcMainAmount();
                // RdsSearchBar.value.clear();
                await uni.hideKeyboard();
                service.enjoyHideLoading();
                diffListManager.value = groupData.value.filter(item => item.c_n_confirm !== item.c_n && item.c_n !== 0);
                // isModified = true;
            } catch (error) {
                console.log("error", error)
                service.enjoyHideLoading();
            }
            break;
        case 'deleteRecCollection':
            await uni.showModal({
                title: '提示',
                content: '是否删除集单，请确认',
                success: async (res) => {
                    if (res.confirm) {
                        service.enjoyShowLoading('正在删除...');
                        await deleteRecCollection(mainDataCollection.value.c_id);
                        service.enjoyHideLoading();
                        await uni.showToast({
                            duration: 2000,
                            icon: 'none',
                            title: '删除成功！'
                        });
                        setTimeout(() => {
                            uni.redirectTo({
                                url: './batchRec?storeId=' + sUserStore.value
                            });
                        }, 300);
                    }
                }
            });
            break;
    }
};
// 获取订货单单据列表信息
const billListByGCode = async () => {
    service.enjoyShowLoading('正在加载...');
    const req = {
        WhereList: [
            {c_col: "c_store_id", c_oper: "等于", c_value: sUserStore.value, c_logic: "而且"},
            {c_col: "c_status", c_oper: "等于", c_value: '0', c_logic: "而且"},
            {c_col: "c_approve_status", c_oper: "等于", c_value: '1', c_logic: "而且"},
            {c_col: "c_po_type", c_oper: "等于", c_value: '521', c_logic: "而且"},
            {c_col: "c_src_id", c_oper: "不为空", c_value: '', c_logic: "而且"},
            mainData.value.c_provider ? {
                c_col: "c_provider",
                c_oper: "等于",
                c_value: mainData.value.c_provider,
                c_logic: "而且"
            } : {},
            mainData.value.c_wno ? {
                c_col: "c_wno",
                c_oper: "等于",
                c_value: mainData.value.c_wno,
                c_logic: "而且"
            } : {},
        ]
    };
    if (searchText.value) {
        req.WhereList.push({c_col: "c_gcode", c_oper: "等于", c_value: searchText.value, c_logic: "而且",});
    }
    const result = await rdsRequest(rdsUrl.scApi, '商品验收单', 'EnjoyQueryList', req, '701');
    service.enjoyHideLoading();
    let _data = result.ReturnObject;
    if (_data.length) {
        await chooseOrder(_data[0].c_id);
    } else if (_data.length > 1) {
        await uni.navigateTo({
            url: './modals/recOrder/index?storeId=' + sUserStore.value + "&orderData=" + JSON.stringify(_data)
        });
    } else {
        const packReq = {
            IuputData: searchText.value
        }
        const packResult = await rdsRequestAsync(rdsUrl.scApi, 'Rds公共服务', 'GetGdsPack',
            packReq,
            '701');
        if (packResult.HasException) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: packResult.Exception.Message,
                mask: true,
            });
            setTimeout(() => {
                RdsSearchBar.value.clear();
            }, 300);
            return;
        }
        if (searchText.value !== packResult.c_gcode) {
            searchText.value = packResult.c_gcode;
            await billListByGCode();
        }
    }
};
const chooseOrder = async (billId) => {
    await billQuery(billId);
    //查询订单是否已集单
    await queryRecCollectionByRecId(billId);
    if (!detailDataCollectionRecId.value.includes(billId)) {
        //没有集单则追单
        await saveRecCollection(billId);
    }
    console.log("detailDataCollectionRecId.value", detailDataCollectionRecId.value, mainData.value.c_id)
    //查询集单下所有的验收单及商品数据
    await queryRecById(mainDataCollection.value.c_id);
    //若选择的订单收过货，则显示收货数据
    await billQueryMiddle('0');
    await openGdsPopup();
};
const billQueryMiddle = async (submitStatus) => {
    
    if (!mainDataCollection.value.c_id) {
        return;
    }
    const req = {
        c_id: detailDataCollectionRecId.value.join(','),
        c_submit_status: submitStatus
        // BillId: mainData.value.c_id,
        // Sql:{ WhereList : [
        //     {c_col: "c_mk_userno", c_oper: "等于", c_value: loginInfo.sUser, c_logic: "而且"},
        //     {c_col: "c_submit_status", c_oper: "等于", c_value: submitStatus, c_logic: "而且"}
        // ]}
    };
    const result = await rdsRequest(rdsUrl.scApi, '商品验收单中间表',
        'EnjoyBillQueryMiddle', req, '701');
    // if (result.ds1.length > 0) {
    detailData.valueMiddleList = result.ds1;
    middleBarCodeList.value.push(...detailData.valueMiddleList.map(x => x
        .c_barcode));
    console.log("middleBarCodeList.value", middleBarCodeList.value)
    console.log("detailData.valueMiddleList", detailData.valueMiddleList)
    const array = groupBy(detailData.valueMiddleList, ['c_barcode']).map(g => ({
        // ...g.keys,
        ...g.groups[0],
        c_n: g.groups.reduce((p, c) => p + c.c_n, 0),
        c_n_free: g.groups.reduce((p, c) => p + c.c_n_free, 0),
        c_n_pack: g.groups.reduce((p, c) => p + c.c_n_pack, 0),
        c_n_odd: g.groups.reduce((p, c) => p + c.c_n_odd, 0),
        // c_n_free_confirm: g.groups.reduce((p, c) => p + c.c_n_free_confirm, 0)
    }));
    
    groupData.value.forEach(x => {
        array.forEach(y => {
            if (x.c_barcode === y.c_barcode) {
                //todo 数量超含量，件数零数计算
                x.c_n = y.c_n;
                x.c_n_free = y.c_n_free;
                x.c_n_pack = y.c_n_pack;
                x.c_n_odd = y.c_n_odd;
                x.c_product_dt = y.c_product_dt;
                x.c_expired_dt = y.c_expired_dt;
                x.c_at_pay = y.c_at_pay;
                x.c_aet_pay = y.c_aet_pay;
                x.c_mk_userno = y.c_mk_userno;
                x.c_submit_status = y.c_submit_status;
                x.c_mk_dt = y.c_mk_dt;
                x.c_note = y.c_note;
                x.c_serial_no = y.c_serial_no;
                // y.c_n_confirm = x.c_n_confirm;
                // y.c_n_free_confirm = x.c_n_free_confirm;
                // y.c_at_pay_order = x.c_at_pay_order;
                // y.c_at_pay = x.c_at_pay;
            }
        });
    });
    
    const middleResult = groupData.value.filter(x => middleBarCodeList.value
        .includes(x.c_barcode));
    console.log("middleResult", middleResult)
    //显示已验收的商品
    c_sku_rec_total.value = middleResult.reduce((pre, current) => pre + (current
        .c_n > 0 || current
        .c_n_free > 0), 0);
    c_n_rec_total.value = middleResult.reduce((pre, current) => pre + (current
        .c_n ?? 0), 0);
    c_n_rec_free_total.value = middleResult.reduce((pre, current) => pre + (current
        .c_n_free ?? 0), 0);
    
    setTimeout(() => {
        RdsSearchBar.value.clear();
    }, 300);
    
    // }
    // else {
    //     // if(submitStatus === '0'){
    //     // }
    //     const itemIndex = listManager.value.findIndex(x => x.c_barcode === c_gcode);
    //     if (itemIndex === -1) {
    //         listManager.value.push(...groupData.value.filter(x => x.c_barcode === c_gcode));
    //         openGdsPopup();
    //     }
    // }
    await calcMainAmount();
};
// 获取集单数据
const queryRecCollectionByRecId = async (billId) => {
    if (!billId) {
        return;
    }
    const result = await rdsRequest(rdsUrl.scApi, '集单收货',
        'EnjoyBillQueryByRecId', billId, '');
    if (result.ds.length > 0) {
        mainDataCollection.value = result.ds[0];
        detailDataCollection.value = result.ds1;
        detailDataCollectionRecId.value = result.ds1.map(x => x.c_order_id);
    }
};
// 获取单据详情信息
const billQuery = async (billId) => {
    if (!billId) {
        return;
    }
    const req = {
        BillId: billId,
    };
    const result = await rdsRequest(rdsUrl.scApi, '商品验收单',
        'EnjoyBillQuery', req, '701');
    if (result.ds.length > 0) {
        mainData.value = result.ds[0];
        detailData.value = result.ds1;
    }
};

// 根据集单号查询验收单和商品
const queryRecById = async (billId) => {
    if (!billId) {
        return;
    }
    const result = await rdsRequest(rdsUrl.scApi, '集单收货',
        'QueryRecById', billId, '');
    if (result?.ds.length > 0) {
        mainData.value = result.ds[0];
        mainDataList.value = result.ds;
        detailData.value = result.ds1;
        //设收货数量为0
        detailData.value.map(x => {
            x.c_n = 0;
            x.c_n_free = 0
        });
        detailDataCollectionRecId.value = mainDataList.value.map(x => x.c_id);
        console.log("detailData.value", detailData.value)
        groupData.value = groupBy(detailData.value, ['c_barcode'])
            .map(g => ({
                // ...g.keys,
                ...g.groups[0],
                c_n_order: g.groups.reduce((p, c) => p + c
                    .c_n_order, 0),
                c_n_free_order: g.groups.reduce((p, c) => p + c
                    .c_n_free_order, 0),
                c_n_confirm: g.groups.reduce((p, c) => p + c
                    .c_n_confirm, 0),
                c_n_free_confirm: g.groups.reduce((p, c) => p +
                    c.c_n_free_confirm, 0)
            }))
        
    }
};
const validateBarcode = async () => {
    let productDtGds = [];
    let excludeDtGds = [];
    let warnMessage = '';
    detailData.value.forEach((x, index) => {
        const isDomestic = isDomesticBarcode(x.c_barcode);
        if (isDomestic) { //国内码
            if (!x.c_product_dt) {
                productDtGds.push(index + 1)
            }
        } else { //国外码
            if (!x.c_expired_dt) {
                excludeDtGds.push(index + 1)
            }
        }
    })
    if (productDtGds.length > 0) {
        warnMessage += `商品第${productDtGds.join(',')}行未录入生产日期`;
    }
    if (excludeDtGds.length > 0) {
        warnMessage += `商品第${excludeDtGds.join(',')}行未录入限用日期`;
    }
    if (warnMessage !== '') {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: warnMessage
        });
        return false;
    }
    return true;
};
//保存集单收货单

const saveRecCollection = async () => {
    const flag = mainDataCollection.value.c_id;
    console.log("mainDataCollection.value.c_id", mainDataCollection.value.c_id, mainData.value)
    if (!flag) {
        const getBillIdReq = {
            BillIdKeyValue: {
                key: "c_id",
                value: ""
            },
            BillVariable: "",
            TableName: "tb_io_rec_collection",
            BillName: "集单收货"
        }
        const billId = await rdsRequest(rdsUrl.mainApi, '单号生成服务',
            'EnjoyGetBillId', getBillIdReq,
            '061');
        if (billId) {
            mainDataCollection.value = {
                c_tenant_id: '',
                c_id: billId,
                c_store_id: mainData.value.c_store_id,
                c_provider: mainData.value.c_provider,
                c_order_count: 1,
                c_gds_kind: detailData.value.length,
                c_rec_wno: mainData.value.c_wno,
                c_type: '',
                c_mk_dt: dayjs().format(
                    'YYYY-MM-DD HH:mm:ss'),
                c_mk_uerno: loginInfo.sUser,
                c_status: '1',
                c_submit_dt: null,
                c_submit_userno: '',
                c_note: '',
            }
        }
    }
    
    //生成集单收货单
    // detailData.value.push({
    //     c_tenant_id: '',
    //     c_id: mainDataCollection.value.c_id,
    //     c_order_id: mainData.value.c_id,
    //     c_gds_kind: detailData.value.length,
    //     c_order_dt: mainData.value.c_au_dt,
    //     c_order_userno: mainData.value.c_au_userno,
    //     c_mk_dt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    //     c_mk_userno: loginInfo.sUser,
    //     c_note: ''
    // })
    
    const newItem = {
        c_tenant_id: '',
        c_id: mainDataCollection.value.c_id,
        c_order_id: mainData.value.c_id,
        c_gds_kind: detailData.value.length,
        c_order_dt: mainData.value.c_mk_dt,
        c_order_userno: mainData.value.c_mk_userno,
        c_mk_dt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        c_mk_userno: loginInfo.sUser,
        c_note: ''
    }
    
    const req = {
        NewList: flag ? [] : [mainDataCollection.value],
        ModifiedList: flag ? [mainDataCollection.value] : [],
        DelList: [],
        TableName: "tb_io_rec_collection",
        PrimaryKeys: ["c_tenant_id", "c_id"],
        ChildData: [{
            ChildTableName: "tb_io_rec_collection_detail",
            ParentTableName: "tb_io_rec_collection",
            ChildColumnNames: ["c_id"],
            ParentColumnNames: ["c_id"],
            ChildSaveModel: {
                NewList: [newItem],
                ModifiedList: [],
                DelList: [],
                TableName: "tb_io_rec_collection_detail",
                PrimaryKeys: ["c_tenant_id", "c_id",
                    "c_order_id"
                ]
            }
        }],
        BillSet: {
            BillIdKeyValue: {
                key: "c_id",
                value: mainDataCollection.value.c_id
            },
            BillVariable: "",
            TableName: "tb_io_rec_collection",
            BillName: "集单收货"
        }
    };
    const result = await rdsRequestAsync(rdsUrl.scApi, '集单收货',
        'EnjoyBillSaveNew', req, '');
    if (result.HasException) {
        //id为空的情况下，保存失败后清空ID
        if (!flag) {
            mainDataCollection.value.c_id = '';
        }
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: result.Exception.Message
        });
        return false;
    }
};

// 保存数据
const saveBill = async () => {
    //验证生产日期
    const result = await validateProduceDt()
    if (!result.validated) {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: result.msg
        });
        return false;
    }
    for (const item of mainDataList.value) {
        const detail = detailData.value.filter(x => x.c_id === item.c_id);
        const req = {
            NewList: [],
            ModifiedList: [item],
            DelList: [],
            TableName: "tb_io_rec",
            PrimaryKeys: ["c_tenant_id", "c_id"],
            ChildData: [{
                ChildTableName: "tb_io_rec_g",
                ParentTableName: "tb_io_rec",
                ChildColumnNames: ["c_id"],
                ParentColumnNames: ["c_id"],
                ChildSaveModel: {
                    NewList: [],
                    ModifiedList: detail,
                    DelList: [],
                    TableName: "tb_io_rec_g",
                    PrimaryKeys: ["c_tenant_id",
                        "c_id", "c_gsort"
                    ]
                }
            }],
            BillSet: {
                BillIdKeyValue: {
                    key: "c_id",
                    value: item.c_id
                },
                BillVariable: "",
                TableName: "tb_io_rec",
                BillName: "商品验收单"
            }
        };
        
        const result = await rdsRequest(rdsUrl.scApi, '商品验收单',
            'EnjoyBillSaveNew', req, '701');
        
    }
    await uni.showToast({
        duration: 2000,
        icon: 'none',
        title: `保存成功`
    });
    return true;
};
const saveBillMiddle = async ({
                                  newItem: newItem,
                                  modifiedItem: modifiedItem,
                                  delItem: delItem,
                                  middleItem: middleItem
                              }) => {
    
    //验证生产日期
    const validateResult = await validateProduceDt();
    if (!validateResult.validated) {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: validateResult.msg
        });
        return false;
    }
    
    // if (newItem) {
    //     newItem.c_mk_userno = loginInfo.sUser;
    //     newItem.c_submit_status = '0';
    //     newItem.c_mk_dt = dayjs().format('YYYY-MM-DD HH:mm:ss.SSS');
    // }
    if (middleItem && !middleItem.c_mk_dt) {
        middleItem.c_mk_userno = loginInfo.sUser;
        middleItem.c_submit_status = '0';
        middleItem.c_mk_dt = dayjs().format('YYYY-MM-DD HH:mm:ss.SSS');
    }
    
    const req = {
        RecCollection: mainDataCollection.value,
        MiddleItem: middleItem ? middleItem : null,
        // NewItem: newItem ? newItem : null,
        // ModifiedItem: modifiedItem ? modifiedItem : null,
        DelItem: delItem ? delItem : null
    }
    const result = await rdsRequest(rdsUrl.scApi,
        '商品验收单中间表', 'EnjoyBillSaveBatch', req, '701');
    console.log("result", result)
    if (result?.Error?.HasException) {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: result.Error.Message
        });
        return false;
    }
    await uni.showToast({
        duration: 2000,
        icon: 'none',
        title: `保存成功`
    });
    return true;
};
const submitBill = async () => {
    
    const result = await rdsRequest(rdsUrl.scApi,
        '商品验收单中间表', 'EnjoyBillSubmitCollection',
        detailDataCollectionRecId.value.join(','), '701'
    );
    if (!result.Result) {
        await uni.showToast({
            duration: 3000,
            icon: 'none',
            title: result.Error.Message
        });
        return false;
    }
    
    await uni.showToast({
        duration: 2000,
        icon: 'none',
        title: `提交成功`
    });
    return true;
};
const canOverOrderValidate = async (ccode, orderN, recN) => {
    
    if (mainData.value.c_price_type !== '9' &&
        recN > orderN) {
        //是否可超收的品类
        if (sysConfig.value.canOverOrderClass.some(
            c => ccode.startsWith(c.c_id) || c
                .c_id.startsWith(
                    ccode))) {
            const rate = isNaN(sysConfig.value
                .recOverOrderRate) ? 0 : sysConfig.value.recOverOrderRate;
            const maxN = (orderN * (1 + rate *
                0.01)).toFixed(3);
            if (recN > maxN) {
                await uni.showToast({
                    duration: 3000,
                    icon: 'none',
                    title: `验收数量超过允许的超收比例${sysConfig.value.recOverOrderRate}%，订货数量${orderN} 验收数量${recN},最多可验收数量${maxN}`
                });
                return false;
            }
        } else {
            await uni.showToast({
                duration: 3000,
                icon: 'none',
                title: `不允许超订单数量验收,订货数量${orderN} 验收数量${recN}`
            });
            return false;
        }
    }
    return true;
};
/**
 * 计算当前金额
 */
const calcRowAmount = async () => {
    currentGds.value.c_at_pay = calcAtInByPt({
        c_pt: currentGds.value.c_pt_pay,
        c_n: currentGds.value.c_n
    });
    currentGds.value.c_at_in = calcAtInByPt({
        c_pt: currentGds.value.c_pt_in,
        c_n: currentGds.value.c_n
    });
    currentGds.value.c_aet_pay = calcAtInByPt({
        c_pt: currentGds.value.c_pet_pay,
        c_n: currentGds.value.c_n
    });
    currentGds.value.c_at_sale = calcAtInByPt({
        c_pt: currentGds.value.c_price,
        c_n: currentGds.value.c_n
    });
};
const calcMainAmount = async (billId) => {
    mainData.value.c_sku_rec = detailData.value
        .reduce((pre, cur) => pre.includes(cur) ?
            pre : [...pre,
                cur
            ], []).length;
    mainData.value.c_n_rec = detailData.value
        .reduce((pre, current) => pre + (Number(
                current.c_n) ?? 0) +
            (Number(current.c_n_free) ?? 0), 0);
    mainData.value.c_at_pay_rec = detailDataList.value.reduce((pre, current) =>
        pre + current.c_at_pay, 0);
    mainData.value.c_aet_pay_rec = detailDataList.value.reduce((pre, current) =>
        pre + current.c_aet_pay, 0);
    mainData.value.c_at_in_rec = detailData.value.reduce((pre, current) => pre + current
        .c_at_in, 0);
    mainData.value.c_at_sale_rec = detailDataList.value.reduce((pre, current) =>
        pre + current.c_at_sale, 0);
};
const converOdUnit = async (odUnit) => {
    let unit = 'd';
    switch (odUnit) {
        case 'D':
            unit = 'd'
            break;
        case 'M':
            unit = 'M'
            break;
        case 'Y':
            unit = 'y'
            break;
    }
    return unit
};
// 列表项样式
const dataListClass = async (item) => {
    // 验收数量和订货数量不一致
    if (item.c_n !== 0 && item.c_n_confirm !== item.c_n) {
        return `m-list-top with-current-gds`;
    } else {
        return `m-list-top`;
    }
};
const validateProductDate = async (productDt) => {
    //如果保质期大于0
    if ((currentGds.value.c_od_day ?? 0) > 0) {
        //到期日期
        let expiredDt = dateAdd(currentGds.value.c_od_day, productDt, await converOdUnit(currentGds.value.c_od_unit))
        expiredDt = dateAdd(-1, expiredDt);
        
        const today = dayjs().format(
            'YYYY-MM-DD');
        //留存天数
        const expiredDays = dateDiff(expiredDt,
            today);
        if (expiredDays <= 0) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '商品已过保质期，不允许收货，请确认！'
            });
            return false;
        }
        
        
        if (currentGds.value.c_od_warning_day) {
            if (expiredDays <= currentGds.value
                .c_od_warning_day) {
                await uni.showToast({
                    duration: 3000,
                    icon: 'none',
                    title: `商品临近保质期，不允许收货！可留存天数（限用日期-收货日期）小于保质期报警天数：${currentGds.value.c_od_warning_day},请确认`
                });
                return false;
            }
        }
        if (!isNaN(sysConfig.value
            .minExpiredPercent) && sysConfig.value.minExpiredPercent !== 0) {
            if (expiredDays / currentGds.value
                .c_od_day * 100 < sysConfig.value
                .minExpiredPercent) {
                await uni.showToast({
                    duration: 3000,
                    icon: 'none',
                    title: `商品临近保质期，不允许收货！可留存天数（限用日期-收货日期）保质期占比低于最低要求${sysConfig.value.minExpiredPercent}%，请确认！`
                });
                return false;
            }
        }
        if (!isNaN(sysConfig.value.exceedOutDate) &&
            sysConfig.value.exceedOutDate < currentGds.value.c_od_day) {
            if (expiredDays < sysConfig.value.exceedOutDate) {
                await uni.showToast({
                    duration: 3000,
                    icon: 'none',
                    title: `商品临近保质期，不允许收货！可留存天数（限用日期-收货日期）小于保质期报警天数：${sysConfig.value.exceedOutDate},请确认`
                });
                return false;
            }
        }
        currentGds.value.c_expired_dt = expiredDt;
        currentGds.value.c_product_dt = productDt;
    }
    return true;
};
const productDtChanged = async (value) => {
    const result = await validateProductDt(value);
    console.log("result",result,value)
    if (!result) {
        currentGds.value.c_product_dt = null;
        return;
    }
    currentGds.value.c_product_dt = value;
    const itemIndex = detailData.value.findIndex( i => i.c_barcode === currentGds.value.c_barcode);
    if (itemIndex !== -1) {
        detailData.value[itemIndex] = currentGds.value;
    }
};
const expiredDtChanged = async (value) => {
    const result = await validateExpiredDt(value);
    if (!result) {
        currentGds.value.c_expired_dt = '';
        return;
    }
    currentGds.value.c_expired_dt = value;
    const itemIndex = detailData.value.findIndex( i => i.c_barcode === currentGds.value .c_barcode);
    if (itemIndex !== -1) {
        detailData.value[itemIndex] = currentGds.value;
    }
};
const validateProductDt = async (value) => {
    if (!value) {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '生产日期不能为空！'
        });
        return false;
    }
    const productDt = value;
    const today = dayjs().format('YYYY-MM-DD');
    if (mainData.value.c_rec_dt) {
        if (mainData.value.c_rec_dt < productDt) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '生产日期不可晚于收货日期！'
            });
            return false;
        }
    } else {
        if (dateDiff(productDt, today) > 0) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '生产日期不能晚于今天!'
            });
            return false;
        }
    }
    if ((currentGds.value.c_od_day ?? 0) === 0) {
        if (currentGds.value.c_expired_dt &&
            dateDiff(productDt, currentGds.value
                .c_expired_dt) > 0) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '限用日期不能早于生产日期!'
            });
            return false;
        }
    }
    return validateProductDate(productDt)
};
/**
 * 验证保质期大于0的商品(有收获数量的商品)，生产日期必填（例外部门除外）
 */
const validateProduceDt = async () => {
    let msg = ''
    let validated = true;
    let mustInputPdtGcodes = []
    let mustInputPdtIds = []
    detailData.value.forEach(i => {
        //重置错误信息
        if (i.c_err_msg) {
            i.c_err_msg = null;
        }
        if (sysConfig.value.isMustInputPdt === '1' &&
            //参数：有保质期商品是否必须录入生产日期
            i.c_od_day > 0 && //保质期大于0
            !i.c_product_dt && //生产日期为空
            (i.c_n_free > 0 || //赠品收获数量
                i.c_n > 0) && //收货数量
            !sysConfig.value.mustInputPdtExceptAdnos.some(adno => i.c_adno.startsWith(adno.value)) //排除例外部门的
        ) {
            const err = [{  c_msg_err: '商品有保质期管理，请录入生产日期' }]
            i.c_err_msg = JSON.stringify(err)
            mustInputPdtIds.push(i.c_id);
            mustInputPdtGcodes.push(i.c_gcode);
        }
    });
    
    const strGcode = mustInputPdtGcodes.join(',');
    if (strGcode) {
        msg = `保存失败！以下商品有保质期管理，请录入生产日期！单号：${mustInputPdtIds.join(',')},商品编码：${strGcode}`;
        validated = false;
    }
    
    return {
        validated,
        msg
    };
};
const validateExpiredDt = async (value) => {
    if (!value) {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '限用日期不能为空！'
        });
        return false;
    }
    const today = dayjs().format( 'YYYY-MM-DD');
    const expiredDt = value;
    if (today > expiredDt) {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '限用日期不能早于今天!'
        });
        return false;
    }
    if ((currentGds.value.c_od_day ?? 0) === 0) {
        if (currentGds.value.c_product_dt && dateDiff(currentGds.value .c_product_dt, expiredDt) > 0 ) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: '生产日期不能晚于限用日期!'
            });
            return false;
        }
    }
    if (currentGds.value.c_od_day) {
        let productDt = dateAdd(1, dateAdd((currentGds.value.c_od_day) * -1,
            expiredDt, await converOdUnit(currentGds.value.c_od_unit)), 'd');
        if (mainData.value.c_rec_dt) {
            if (productDt > mainData.value.c_rec_dt) {
                await uni.showToast({
                    duration: 2000,
                    icon: 'none',
                    title: `商品生产日期不可晚于收货！根据商品保质期反算生产日期为[${productDt}]！`
                });
                return false;
            }
        } else if (productDt > today) {
            await uni.showToast({
                duration: 2000,
                icon: 'none',
                title: `商品生产日期不可晚于今天！根据商品保质期反算生产日期为[${productDt}]！`
            });
            return false;
        }
        const result = validateProductDate(productDt)
        return result
    }
    return true;
};
const getGdsInfo = async (gcode) => {
    const req = {
        WhereList: [{
            c_col: "c_store_id",
            c_oper: "等于",
            c_value: sUserStore.value,
            c_logic: "而且"
        },
            {
                c_col: "inputOrigMode",
                c_logic: "而且",
                c_value: "1",
                c_oper: "等于"
            },
            {
                c_col: "c_gcode",
                c_oper: "等于",
                c_value: gcode,
                c_logic: "而且"
            }
        ]
    };
    const result = await rdsRequest(rdsUrl
            .bcApi, '弹窗通用查询',
        'FetchComplexGds', req);
    if (result.ReturnObject.length > 0) {
        return result.ReturnObject[0]
    }
    return gcode;
};
const enjoyConfirm = async (e) => {
    return new Promise((resolve) => {
        uni.showModal({
            title: '提示',
            content: e,
            success: (
                res
            ) => {
                if (res
                    .confirm
                ) {
                    resolve
                    (
                        true);
                } else {
                    resolve
                    (
                        false);
                }
            }
        });
    });
};
// 切换录入方式
const toggleMode = async (value) => {
    inputMode.value = value;
};
const change = async (e) => {
    isOpened.value = e;
    console.log('返回：', e);
};
const bindClick = async (e, index) => {
    console.log("e,index", e, index);
    await uni.showModal({
        title: ' 提示',
        content: '您确定要删除数据吗？',
        showCancel: true,
        success: async (
            res) => {
            if (res
                .confirm) {
                await saveBillMiddle({
                    delItem: listManager.value[index]
                });
                middleBarCodeList.value =
                    await removeElement(
                        middleBarCodeList.value,
                        listManager.value[index].c_barcode
                    );
                await billQueryMiddle('0');
            }
        }
    });
};
const removeElement = async (array, elementToRemove) => {
    return array.filter(item =>
        item !== elementToRemove);
};

const bindClickCollection = async (e, index) => {
    if (mainDataList.value.length === '1') {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '至少有一张单据！'
        });
        return;
    }
    await uni.showModal({
        title: ' 提示',
        content: '您确定要删除数据吗？',
        showCancel: true,
        success: async (
            res) => {
            if (res.confirm) {
                await deleteRecCollectionDetail({
                    delItem: mainDataList.value[index]
                });
                await queryRecById(mainDataCollection.value.c_id);
                await billQueryMiddle('0');
                mainDataList.value.splice(index, 1);
            }
        }
    });
};
//删除集单收货明细
const deleteRecCollectionDetail = async ({delItem: delItem}) => {
    const req = {
        NewList: [],
        ModifiedList: [],
        DelList: [],
        TableName: "tb_io_rec_collection",
        PrimaryKeys: [
            "c_tenant_id",
            "c_id"
        ],
        ChildData: [{
            ChildTableName: "tb_io_rec_collection_detail",
            ParentTableName: "tb_io_rec_collection",
            ChildColumnNames: [
                "c_id"
            ],
            
            ParentColumnNames: [
                "c_id"
            ],
            ChildSaveModel: {
                NewList: [],
                ModifiedList: [],
                DelList: delItem ? [] : [
                    delItem
                ],
                TableName: "tb_io_rec_collection_detail",
                PrimaryKeys: [
                    "c_tenant_id",
                    "c_id",
                    "c_order_id"
                ]
            }
        }],
        BillSet: {
            BillIdKeyValue: {
                key: "c_id",
                value: mainDataCollection.value.c_id
            },
            BillVariable: "",
            TableName: "tb_io_rec_collection",
            BillName: "集单收货"
        }
    };
    const result = await rdsRequest(rdsUrl.scApi, '集单收货', 'EnjoyBillSaveNew', req, '');
};
//删除集单收货单
const deleteRecCollection = async (billId) => {
    if (!billId) {
        return;
    }
    const result =
        await rdsRequest(rdsUrl.scApi, '集单收货', 'DeleteCollection', billId, '');
};
</script>

<style lang="scss" scoped>
@import '@/static/font/enjoyicon/iconfont.css';
@import '@/main.scss';
::v-deep .white-main {
  margin: 20rpx 0;
}
.content-img {
    background-color: #FFFFFF;
    background-size: 100% 176rpx;
    background-repeat: no-repeat;
    width: 100%;
}

.custom-menu {
    // border-top: 1px solid rgba(0, 0, 0, .1);
    display: flex;
    flex: 1;
    width: 100%;
    padding: 0px 10px 0px 10px;
    justify-content: flex-start;
}

.setting-item {
    display: flex;
    align-items: center;
    font-size: 0.8em;
    margin: 0.5em;
    padding: 0.5em;
}

.setting-desc {
    display: flex;
    justify-content: flex-start;
    flex: 1;
    width: 100%;
    font-size: 0.8em;
    // margin: 0;
    padding: 0.5em;
}

.extra-view {
    margin-right: 30rpx;
    font-size: 12px;
    color: #0099ff
}

.bt-button {
    background-color: #FFFFFF;
    padding: 10rpx 0rpx;
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.popup-icon-btn {
    display: flex;
    padding: 10px;
    margin: 5px;
    color: #333333;
    text-align: center;
    flex-direction: column;
}

.popup-icon-btn uni-icon {
    margin: 0 auto;
    background: #ffffff;
    border-radius: 50%;
    font-size: 1.2em;
    width: 42px;
    height: 42px;
    line-height: 42px;
    text-align: center;
}

.popup-icon-btn uni-text {
    font-size: 0.8em;
    padding: 0.2em 0;
    line-height: 1.4em;
    width: 52px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

// 业务自定义
.icon_new_count {
    color: #00aaff;
}

.top-view {
    width: 100%;
    height: 88rpx;
    background: #FFFFFF;
}

.footer-view {
    width: 100%;
    flex: 1;
}

.m-main-top {
    width: 100%;
    display: grid;
    grid-template-columns: 51% 49%;
    font-size: 12px;
}

.m-list-top {
    width: 100%;
    display: grid;
    grid-template-columns: 51% 49%;
    border-bottom: 1px solid #c8c7cc;
    font-size: 12px;
}


.m-list-top {
    width: 100%;
    display: grid;
    grid-template-columns: 51% 49%;
    padding: 0px 6px 0px 6px;
    border-bottom: 1px solid $uni-border-color;
    font-size: 12px;
}

.popup-content {
    align-items: center;
    justify-content: flex-start;
    flex-direction: column;
    padding: 0 20rpx 20rpx 20rpx;
    background-color: #ffffff;
    border-radius: 20rpx 20rpx 0 0;
}

.image-min {
    width: 100%;
    height: 150rpx;
    opacity: 0.6;
    margin-top: -20rpx;
}

.no-data-text {
    text-align: center;
    color: #cccccc;
    font-size: 26rpx;
    margin-top: -20rpx;
}

.popup-height {
    width: 200px;
}

.popup-content-message {
    align-items: center;
    justify-content: left;
    flex-direction: column;
    padding: 0 20rpx 20rpx 20rpx;
    width: 600rpx;
    background-color: #ffffff;
    border-radius: 20rpx 20rpx 0 0;
}

.popup-title {
    width: 100%;
    height: 84rpx;
    background: #FFFFFF;
    border-radius: 40rpx 40rpx 0 0;
    display: flex;
    justify-content: center;
    align-items: center;
    color: $uni-text-color-secondary;
    font-size: $uni-font-size-level1;
    line-height: 45rpx;
    text-align: center;
    position: relative;
}
</style>
